package com.org.redis.lock;

import com.org.redis.config.RedisTemplate;
import com.org.redis.config.RedissonConfig;
import org.redisson.Redisson;
import org.redisson.api.RLock;

public class Lock {

    public static void main(String[] args) {
        Redisson redisson = RedissonConfig.getRedisson();
        String lockKey = "wang";
        RLock lock = redisson.getLock(lockKey);
        try {
            //如果加锁成功，每后台会开启一个线程，每10秒检查是否还持有锁，如果持有则延迟加锁时间
            //自旋锁，如果加锁不成功就一直尝试加锁
            lock.lock(); //相当于jedis的 setnx
            /** 业务代码 **/
        }catch (Exception e){
        }finally {
            lock.unlock();
        }
    }

    public static void lock() {
        String lockKey = "wang";
        RedisTemplate redisTemplate = new RedisTemplate();
        try {
            redisTemplate.set(lockKey, "1", 10);
            /** 业务代码 **/
        } finally {
            redisTemplate.delete(lockKey);
        }
    }
}
